package util;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;

/**
 * Visitor for retrieving AST node information.
 * 
 */
public class Visitor extends ASTVisitor {
	List<TypeDeclaration> classes = new ArrayList<TypeDeclaration>();
	List<MethodDeclaration> methods = new ArrayList<MethodDeclaration>();
	List<VariableDeclarationFragment> variables = new ArrayList<VariableDeclarationFragment>();

	  @Override
	  public boolean visit(TypeDeclaration node) {
		  classes.add(node);
	    return super.visit(node);
	  }

	  public List<TypeDeclaration> getClasses() {
	    return classes;
	  }

	@Override
	public boolean visit(MethodDeclaration node) {
		methods.add(node);
		return super.visit(node);
	}

	public boolean visit(VariableDeclarationFragment node) {
		variables.add(node);
		return false;
	}

	public List<MethodDeclaration> getMethods() {
		return methods;
	}

	public List<VariableDeclarationFragment> getVariables() {
		return variables;
	}
	
	/**
	 * creates a AST tree based on the ICompilationUnit passed in
	 * @param iUnit
	 * @return a CompilationUnit
	 */
	public static CompilationUnit parse (ICompilationUnit iUnit){
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(iUnit);
		parser.setResolveBindings(true);
		return (CompilationUnit) parser.createAST(null);
	}
}